<template>
	<div class="u-page" style="background:#f7f7f7">
		<section class="aui-flexView">
			<section class="aui-scrollView">
					
				<!-- <div class="aui-choice-white u-pt-15 u-pb-15">
					<div style="width: 93%;margin: 0 auto;">
						<h1>样品清单（样品剩余{{form.remainQuota?form.remainQuota:0}}个）</h1>
					</div>
				</div> -->

				<div class="aui-choice-white u-pt-15 u-pb-15">
					<div style="width: 93%;margin: 0 auto;" @click="toSelectAddress">
						<div style="display: flex;justify-content: space-between;align-items: center;" v-if="JSON.stringify(addressObj) !== '{}'">
							<div class="cont-right">
								<div class="u-flex u-fz-13">
									<span v-if="addressObj.DefaultStatus == 1">
										<div class="default-tag">默认</div>
									</span>
									<span class='address1'>{{addressObj.Region.replace(/'-'/g, '')}}-{{addressObj.StreetVillage.replace(/'-'/g, '')}}</span>
								</div>
								<div class="u-title u-fz-20 u-pt-5" v-if="addressObj.Address">{{addressObj.Address}}</div>
								<div class="u-pt-5 u-fz-15">
									<span>{{addressObj.Name}}</span>
									<span class="u-pl-5">{{addressObj.PhoneNum}}</span>
								</div>
							</div>
							<div>
								<u-icon name="arrow-right" color="#d6d2d2" size="28"></u-icon>
							</div>
						</div>
						<div v-else>
							<div class="aui-choice-white" style="display: flex;justify-content: space-between;">
								<div class="u-title u-fz-20">请选择收货地址</div>
								<div class="u-flex u-col-center">
									<div class="u-center">
										<u-icon name="arrow-right" color="#d6d2d2" size="28"></u-icon>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
				
				<div class="aui-choice-white border-radius-30">
					<div class="aui-flex aui-flex-default u-mt-10" @click="toGoodsDetails">
						<div class="aui-flex-goods">
							<img :src="form.goodsImages.split(',')[0]" alt="">
						</div>
						<div class="aui-flex-box">
							<div class="solitaire-title">
								{{form.subject}}
							</div>
							<div class="u-fz-13" style="color: #9f9d9e;">{{form.specification}}</div>
							<div class="aui-flex aui-flex-clear u-pt-5" style="display: flex;justify-content: space-between;">
								<div class="u-fz-19 u-font-bold" style="color: #ea4d5e;">&yen;{{form.discountPrice}}</div>
								x1
							</div>
						</div>
					</div>
					
					<div class="aui-flex2">
					  <div class="aui-flex-box">是否使用钱包余额抵扣</div>
						<div class="aui-flex-triangle" @click="useDeduction_show = true">{{useDeduction_text}}</div>
						<u-picker v-model="useDeduction_show" mode="selector" :default-selector="[1]" :range="useDeductionRange" range-key="lable"
							@confirm="selectDeduction"></u-picker>
					</div>
					
					<!-- 使用钱包余额抵扣 -->
					<div v-if="useDeduction == '1'">
						<div class="aui-flex2">
							<div class="aui-flex-box">抵扣金额</div>
							<div style="color: #f21956;">-&yen;{{deductionAmount}}</div>
						</div>
						
						<div class="aui-flex2">
							<div class="aui-flex-box">钱包剩余金额</div>
							<div>&yen;{{remainAmount}}</div>
						</div>
					</div>
					
					<div class="aui-flex2">
						<div class="aui-flex-box">配送</div>
						<div>快递包邮</div>
					</div>
					<div class="aui-flex2">
						<div class="aui-flex-box">备注</div>
						<u-input v-model="orderRemarks" input-align="right" :placeholder-style="(remarkSwitch&&form.remarkReminder)?'color:red;':''" :placeholder="form.reminderContent?form.reminderContent:'如有其他要求,请填写备注'"></u-input>
					</div>
				</div>
				
				<!-- <div class="aui-choice-white border-radius-30">
					<div style="width: 93%;margin: 0 auto;padding-bottom: 40rpx;">
						<div style="margin: 20rpx 0rpx;padding-top: 30rpx;font-weight: bolder;font-size: 30rpx;">
							区域服务商
						</div>
						<div v-if="supplierList && supplierList.length > 0">
							<u-radio-group @change="radioGroupChange" v-model="selectedSupplierId" active-color="#e55e97">
								<u-radio v-for="(item, index) in supplierList" :key="index" :name="item.id">
									<div class="u-flex u-row-between u-col-center u-mb-5 u-pt-10 u-pl-10">
										<u-avatar :src="item.images" size="100" mode="square"></u-avatar>
										<div class="u-col-center u-flex-1 u-pl-10">
											<div class="u-title">
												{{item.storeName?item.storeName:''}}
											</div>
											<div class="commodity-no u-fz-13">{{item.address}}</div>
										</div>
									</div>
								</u-radio>
							</u-radio-group>
						</div>
					</div>
				</div> -->
				
			</section>
			
			<p class="v-sperate"></p>
			<section class="aui-scrollView aui-choice-white m-pt-15 m-pb-15">
				<div class="modal-item" @click="showRules">
					<div style="font-weight: bold;">
						【非常重要！请仔细阅读！】
					</div>
					<div class="u-pr-15" style="font-size: smaller;">
						<u-icon :name="iconName" color="#9f9d9e" size="24"></u-icon>
					</div>
				</div>
				
				<div v-if="show_rule">
					<div class="rule-title">
						试用要求
					</div>
					<div class="rule-content">
						<u-parse :html="this.escape2Html2(form.requiredContent)"></u-parse>
					</div>
					
					<div class="rule-title">
						评级标准
					</div>
					<div class="rule-content">
						<u-parse :html="this.escape2Html2(form.ratingCriteria)"></u-parse>
					</div>
					
					<div class="rule-title">
						领取规则
					</div>
					<div class="rule-content">
						<u-parse :html="this.escape2Html2(claimRules)"></u-parse>
					</div>
				</div>
			</section>
			
			<div style="height: 250rpx;"></div>

			<div class="aui-bar-footer">
				<div class="u-pb-5">
					<div class="notice-bar" @click="followOfficialAccount">
						<span style="text-decoration: underline;">关注公众号</span>，及时获取物流进度。
					</div>
				</div>
				<div class="aui-flex">
					<div class="aui-flex-box">
						应付金额：<span>&yen;{{temp_PayAmount}}</span>
					</div>
					<div>
						<u-button :disabled="isClick"
							:custom-style="{background:'#e55e97',padding:'52rpx 50rpx',color:'#fff',fontSize:'28rpx',borderRadius:'0rpx'}"
							hover-class="none" @click="placeOrder">领取样品</u-button>
					</div>
				</div>
			</div>

		</section>

		<!-- 是否确认领取 -->
		<u-modal v-model="buy_show" confirm-text="确认" show-cancel-button :content="buy_show_text" @confirm="confirmBuy">
		</u-modal>
		
		<!-- 再次执行“订单是否支付成功”查询 -->
		<u-modal ref="uModal" title="平台提示" v-model="payInfo_show" confirm-text="确认"
			@confirm="doQueryWxPayOk('second')">
			<div class="u-p-20">
				<p>订单未支付成功，请重试！</p>
			</div>
		</u-modal>
		
		<!-- 选择支付的方式 -->
		<u-popup v-model="payType_show" mode="bottom" @close="closePopup">
			<div class="popup-box">
				<div class="popup-item" v-for="(item, index) in chooseTypes" @click="clickPopup(item)">
					<div>{{item.text}}</div>
				</div>
			</div>
		</u-popup>
		
		<!-- 关注公众号 -->
		<u-mask :show="official_account_show" :mask-click-able="false" z-index="9999">
			<div class="mask-solt">
				<div>
					<div class="official-account-bg"></div>
					<div class="u-mt-15 mask-close" @click="closeOfficialAccount">
						<u-icon name="close-circle" color="rgb(68,68,68)" size="45"></u-icon>
					</div>
				</div>
			</div>
		</u-mask>
		
	</div>
</template>

<script>
	import globalData from "@/globalData";
	export default {
		data() {
			return {
				form: {}, // 活动详情
				orderRemarks: '',// 订单备注
				orderDetail: {},// 领取记录详情
				isClick: false,
				buy_show: false,
				buy_show_text: '',
				addressObj: {}, // 收货地址
				// supplierList: [], // 匹配到的供应商列表
				// selectedSupplier: {}, // 选中的供应商
				// selectedSupplierId: '', // 选中的供应商记录唯一id
				official_account_show: false,// 关注公众号弹窗
				payInfo_show: false,
				payType_show: false,
				PrivilegedStatus: '', // 是否为支付特权人员。yes:是；no:否。默认：no
				chooseTypes: [{
						text: '全额付款',
						action: 'fullPayment'
					},
					{
						text: '支付0.01元',
						action: 'payALittle'
					},
					{
						text: '取消',
						action: 'closePopup'
					}
				],
				remarkSwitch: false,
				show_rule: true,
				claimRules: '领取样品后，需完成产品试用，并按照试用要求提交评价，达到评级标准的平台会发放相应的报酬！如未完成评价，则会限制您继续参与其他样品活动，敬请谅解～',
				iconName: 'arrow-down',
				officialAccountUrl: 'https://mp.weixin.qq.com/s/IYKtVOzoorlNeIXBB4yhjQ',
				useDeduction_show: false,
				useDeduction_text: '否',// 是否使用钱包余额抵扣
				useDeduction: '0',
				useDeductionRange: [
					{
						id: '1',
						lable: '是'
					},
					{
						id: '0',
						lable: '否'
					}
				],
				walletTotalAmount: 0.00,// 钱包总金额
				deductionAmount: 0.00,// 抵扣金额
				remainAmount: 0.00,// 抵扣后的剩余金额
				amountBeforeDeduction: 0.00,// 记录抵扣前的实付金额
				temp_PayAmount: 0.00, // 用于记录应付金额
			}
		},

		onLoad(options) {

			// 未登录跳转到登录页面
			var loginRes = this.checkLogin()
			if (!loginRes) {
				return false;
			}

			let info = decodeURIComponent(options.info)
			if (this.isNotNull(info)) {
				this.form = JSON.parse(info)
				this.temp_PayAmount = this.form.samplePrice;
				console.log("form=", this.form)
			} else {
				if (this.isNotNull(options.docUnid)) {
					this.getActivityDetails(options.docUnid);
				} else {
					this.showMSG('error', '出错啦！')
					setTimeout(() => {
						this.goBack()
					}, 2500)
				}
			}
			
			// 选中的收货地址
			uni.$on("AddressObj", (obj = {}) => {
				this.addressObj = obj;

				/* // 获取供货商
				this.getSupplierList(this.addressObj); */
			});

			// 获取默认收货地址
			if (JSON.stringify(this.addressObj) === '{}') {
				this.getDefaultAddress();
			}
			/* else {
				// 获取供货商
				this.getSupplierList(this.addressObj);
			} */
			
			// 锁定名额
			this.lockedQuota();
			
			// 根据userid获取支付特权状态
			this.getPrivilegedStatus();
			
			// 获取用户钱包金额
			this.getWalletAmount();
		},

		methods: {
			
			/**
			 * 判断用户是否享有支付特权
			 */
			async getPrivilegedStatus() {
				const userInfo = uni.getStorageSync('userInfo')
				let result = await this.$u.api.unifyMiniRestGet({
					systemid: "meily",
					url: "/user/canQuickPay/" + userInfo.userId,
					loading: false // 默认发起请求会有一个全局的Loading，设置false可去掉
				});
				if (result.code == 200) {
					this.privilegedStatus = result.data
				}
			},
			
			/**
			 * 获取用户钱包金额
			 */
			async getWalletAmount(){
				const userInfo = uni.getStorageSync('userInfo')
				let res = await this.$u.api.unifyMiniRest({
					systemid: "payment",
					url: "/points/token",
					userId: userInfo.userId,
					loading: false
				});
				if(res.code == 200 && this.isNotNull(res.data)){
					let token = res.data
					let tmpToken = this.sault_md5_token(token)
					let result = await this.$u.api.unifyMiniRest({
						systemid: "payment",
						url: "/wallet/getCoins",
						userId: userInfo.userId,
						token: token,
						authStr: tmpToken,
						loading: false
					});
					if(result.code == 200 && result.data){
						this.walletTotalAmount = result.data;// 钱包总余额
						this.remainAmount = this.walletTotalAmount;
					}
				} else {
					this.showMSG('none','获取token出错啦')
				}
			},
			
			/**
			 * 是否使用钱包余额抵扣
			 * @param {Object} e
			 */
			selectDeduction($event) {
				let obj = this.useDeductionRange[$event]
				this.useDeduction = obj.id;
				this.useDeduction_text = obj.lable;
				
				// 使用抵扣前，需要记录抵扣前的实付金额，否则若再次选择不使用抵扣时，无法重新计算不使用抵扣的金额
				this.amountBeforeDeduction = this.form.samplePrice;
				
				// 计算抵扣金额
				this.calculateDeductionAmount();
			},
			
			/**
			 * 计算抵扣金额
			 */
			calculateDeductionAmount(){
				// 1.使用抵扣
				if(this.useDeduction == '1'){
					console.log("********使用抵扣*****")
					// 更改实付金额
					if (this.isNotNull(this.temp_PayAmount) && parseFloat(this.temp_PayAmount) > 0){
						// 情况1：部分抵扣：钱包金额 > 实付金额
						if(parseFloat(this.walletTotalAmount) > parseFloat(this.temp_PayAmount)){
							this.remainAmount = (parseFloat(this.walletTotalAmount).toFixed(2) - parseFloat(this.temp_PayAmount).toFixed(2)).toFixed(2);
							this.deductionAmount = this.temp_PayAmount;
							this.temp_PayAmount = 0.00
						} else {
							// 情况2：全部抵扣：实付金额 >= 钱包金额
							this.remainAmount = 0.00;
							this.deductionAmount = this.walletTotalAmount;
							this.temp_PayAmount = (parseFloat(this.temp_PayAmount).toFixed(2) - parseFloat(this.walletTotalAmount).toFixed(2)).toFixed(2);
						}
					}
				} else if(this.useDeduction == '0'){
					console.log("********不使用抵扣*****")
					// 2.不使用抵扣
					if(this.isNotNull(this.amountBeforeDeduction)){
						this.temp_PayAmount = this.amountBeforeDeduction;
						this.deductionAmount = 0.00;
					}
				}
			},
			
			/**
			 * 获取活动详情
			 */
			async getActivityDetails(docUnid) {
				let result = await this.$u.api.unifyMiniRestGet({
					systemid: "meily",
					url: "/provide/samples/info/" + docUnid,
					loading: true // 默认发起请求会有一个全局的Loading，设置false可去掉
				});
				if (result.code == 200) {
					this.form = result.data; // 活动详情
					this.temp_PayAmount = this.form.samplePrice;
				} else {
					this.$u.toast(result.msg)
				}
			},

			/**
			 * 获取默认收货地址（BPM）
			 */
			async getDefaultAddress() {
				const userInfo = uni.getStorageSync('userInfo')
				let result = await this.$u.api.unifyMiniRest({
					systemid: "meily",
					url: "/minrest",
					appid: 'meily',
					wf_num: 'R_meily_BL014',
					userId: userInfo.userId,
					nickName: userInfo.nickName,
					loading: false // 默认发起请求会有一个全局的Loading，设置false可去掉
				});
				if (result.code == '200') {
					if (result.data) {
						this.addressObj = result.data;

						/* // 获取供货商
						this.getSupplierList(this.addressObj); */
					}
				}
			},

			/**
			 * 获取供货商
			 */
			async getSupplierList(addressObj) {

				let address = "";
				if (this.isNotNull(addressObj.Region) && this.isNotNull(addressObj.StreetVillage)) {
					address = addressObj.Region + "-" + addressObj.StreetVillage;
				}
				let result = await this.$u.api.unifyMiniRest({
					systemid: "meily",
					url: "/provider/match",
					address: address,
					loading: false // 默认发起请求会有一个全局的Loading，设置false可去掉
				});

				if (result.code == '200') {
					if (result.rows) {
						this.supplierList = result.rows;
						if (this.supplierList.length == 1) {
							this.selectedSupplierId = this.supplierList[0].id;
							this.selectedSupplier = this.supplierList[0];
						}
					}
				}
			},

			/**
			 * 锁定名额
			 */
			async lockedQuota(){
				let result = await this.$u.api.unifyMiniRest({
					systemid: "meily",
					url: "/provide/samples/sub/lockedQuota",
					partnerId: uni.getStorageSync('userInfo').userId,// 参与者id
					partnerName: uni.getStorageSync('userInfo').nickName,// 参与者昵称
					partnerAvatarUrl: uni.getStorageSync('userInfo').avatarUrl,// 参与者头像
					initiatorId: this.form.initiatorId,
					initiatorName: this.form.initiatorName,
					subject: this.form.subject,
					joinEndTime: this.form.joinEndTime,
					endTime: this.form.joinEndTime,
					mainId: this.form.id,
					mainTaskNumber: this.form.taskNumber,
					sceneAssetsId: this.form.sceneAssetsId,
					sceneId: this.form.sceneId,
					samplePrice: this.form.samplePrice,
					goodsId: this.form.goodsId,
					goodsNo: this.form.goodsNo,
					goodsName: this.form.goodsName,
					goodsImages: this.form.goodsImages,
					specification: this.form.specification,
					orderStatus: '待支付',
					loading: true ,// 默认发起请求会有一个全局的Loading，设置false可去掉
				});
				if (result.code == 200) {
					this.orderDetail = result.data;// 锁定名额时返回的领取记录详情
					
				} else if(result.code == 203){// 已报名
					setTimeout(() => {
						this.$u.route(result.url)
					}, 1500)
				} else if(result.code == 205){// 测评师资料尚未填写完毕
					this.checkEvaluatorInfo_show = true;
					
				} else if (result.code == 207){// 未注册“区域服务商”
					this.checkRegisterProvider_show = true;
					
				} else {// 其他情况
					// 设置按钮为可点击
					this.isClick = false;
					this.$u.toast(result.msg)
				}
			},
			
			/**
			 * 提交订单
			 */
			async placeOrder() {
				
				// 第1步 判断是否已经选择了收货地址
				if (JSON.stringify(this.addressObj) === '{}') {
					this.$u.toast("请选择收货地址！");
					return
				} else if(!this.isNotNull(this.addressObj.Name)){
					this.$u.toast("收货人姓名不能为空！");
					return;
				} else if(!this.verificationName(this.addressObj.Name)){
					this.$u.toast("收货人姓名至少包含一个字母或一个中文！");
					return;
				} else if(!this.isNotNull(this.addressObj.PhoneNum)){
					this.$u.toast("手机号码不能为空！");
					return;
				} else if(!this.verificationPhone(this.addressObj.PhoneNum)){
					this.$u.toast("手机号码不合法！");
					return;
				} else if(!this.isNotNull(this.addressObj.Region) || !this.isNotNull(this.addressObj.StreetVillage) || !this.isNotNull(this.addressObj.Address)){
					// 检验地址是否填写完毕
					this.$u.toast("地址信息尚未完整！");
					return;
				} else if (JSON.stringify(this.selectedSupplier) === '{}') {
					// 第2步 判断是否已经选择了供应商
					this.$u.toast("请选择供应商！");
					return
				} else if(this.form.remarkReminder==1 && !this.isNotNull(this.orderRemarks)) {
					this.remarkSwitch = true
					this.$u.toast("请填写备注！");
					return;
				} else {
					this.buy_show_text = "领取1件商品，需要支付" + this.form.samplePrice + "元，您确认领取吗？";
					this.buy_show = true;
				}
			},
			
			/**
			 * 确定领取
			 * 1. 先支付
			 * 2. 后保存接龙记录
			 */
			async confirmBuy() {
				// 支付。判断用户是否享有支付特权
				if (this.privilegedStatus == "yes") {
					// 是，则可以选择支付额度
					this.payType_show = true;
				} else {
					// 否，全额付款
					this.doWxPay('fullPayment');
				}
			},
			
			/**
			 * 选择支付的方式
			 */
			async clickPopup(item) {
				if (item.action == 'fullPayment' || item.action == 'payALittle') {
					this.doWxPay(item.action);
				} else if (item.action == 'closePopup') {
					this.payType_show = false;
				}
			},
			
			/**
			 * 关闭 选择支付的方式
			 */
			closePopup() {
				this.payType_show = false;
			},
			
			/**
			 * 支付
			 */
			async doWxPay(action) {
				
				// 支付订单ID
				this.form.orderId = this.guid();// 商户订单号。可自定义也可让系统自动生成
				
				this.form.samplePrice = this.temp_PayAmount;
			
				// 显示 loading 提示框
				uni.showLoading({
					mask: true,
				});
			
				// 设置按钮为不可点击
				this.isClick = true;
			
				// 0.初始化订单信息
				// 格式化名字（名字超长处理）--- 暂不处理
				let Subject = this.formatSubject(this.form.subject, 25);
			
				let name = Subject + "-支付领取样品费用";
				let price = 0;
			
				if (action == 'fullPayment') {
					console.log("********全额付款***********");
					price = parseFloat(this.form.samplePrice) * 100; // 全额付款
				}
				if (action == 'payALittle') {
					console.log("********支付0.01元***********");
					price = 1; // 支付一分钱
				}
			
				// 定义商品信息串，建议这些字段定义规范并且固定（例如商品件数等数据），好方便订单系统进行展示
				let goodsInfo = {};
				goodsInfo.goodsNum = '1件'; // 件数
				goodsInfo.goodsWeight = '0kg'; // 重量
			
				// 定义商家信息串，建议这些字段定义规范并且固定（例如下面这两个字段），好方便订单系统进行展示
				let mchInfo = {};
				mchInfo.mchname = ""; // 商家名称
				mchInfo.mchimage = ""; // 商家图标
			
				let obj = {};
				obj.userid = uni.getStorageSync('userInfo').userId;
				obj.openid = uni.getStorageSync('userInfo').openid;
				obj.tradeDesc = name;
				obj.payPrice = price; // 付款金额
				obj.productID = this.form.goodsNo; // 商品编号
				obj.productUrl = ''; // 订单详情页地址
				obj.imageUrl = this.form.goodsImages.split(',')[0]; // 商品图片
				obj.goodsInfo = goodsInfo;
				obj.mchInfo = mchInfo;
				obj.remark = name;
				obj.tradeNo = this.form.orderId;
				let businessData = {
					id: this.orderDetail.id,// 领取记录唯一id
					partnerId: uni.getStorageSync('userInfo').userId,// 参与者id
					partnerName: uni.getStorageSync('userInfo').nickName,// 参与者昵称
					partnerAvatarUrl: uni.getStorageSync('userInfo').avatarUrl,// 参与者头像
					initiatorId: this.form.initiatorId,
					initiatorName: this.form.initiatorName,
					subject: this.form.subject,
					joinEndTime: this.form.joinEndTime,
					endTime: this.form.joinEndTime,
					mainId: this.form.id,
					mainTaskNumber: this.form.taskNumber,
					sceneAssetsId: this.form.sceneAssetsId,
					sceneId: this.form.sceneId,
					consigneeName: this.addressObj.Name,// 收货人姓名
					consigneePhoneNum: this.addressObj.PhoneNum,// 手机号码
					consigneeAddress: this.addressObj.Region + "-" + this.addressObj.StreetVillage + " " + this.addressObj.Address,// 收货地址
					orderRemarks: this.orderRemarks,// 订单备注
					/* supplierId: this.selectedSupplier.userId,
					supplierName: this.selectedSupplier.nickName,
					supplier: JSON.stringify(this.selectedSupplier), */
					samplePrice: this.form.samplePrice,
					goodsId: this.form.goodsId,
					goodsNo: this.form.goodsNo,
					goodsName: this.form.goodsName,
					goodsImages: this.form.goodsImages,
					specification: this.form.specification,
					orderStatus: '待发货',
					orderId: this.form.orderId,
					quantity: "1",
					payAmount: this.form.samplePrice,
					useDeduction: this.useDeduction,// 是否使用抵扣
					deductionAmount: this.deductionAmount,// 抵扣金额
				};
				let orderExtJson = {
					type: 1,// 领取样品
					data: businessData // 业务数据
				}
				obj.orderExtJson = JSON.stringify(orderExtJson);
			
				// 1.调用微信支付接口鉴权，返回鉴权信息
				let authinfo = await this.geAuthInfo(obj);
				console.info("支付接口1.authinfo=", authinfo);
				if (authinfo.code != 200) {
					console.log("鉴权失败：" + authinfo);
					this.showMSG('error', '支付失败！');
					this.isClick = false; // 设置按钮为可点击
					return;
				}
			
				// 2.调用 小程序支付统一接口，这里是以url判断是哪个接口的
				let url = "/api/unifiedorder";
				let respJson = await this.postWxpayServer(url, obj, authinfo);
				console.info("支付接口2.respJson=", respJson);
				if (respJson.code != 200) {
					console.log("调用小程序支付统一接口失败：" + respJson.msg);
					this.showMSG('error', '支付失败！');
					this.isClick = false; // 设置按钮为可点击
					return;
				}
				
				// 3.开始发起支付动作
				let paymentdata = respJson.data;
				console.log("支付接口3.paymentdata=", paymentdata);
				// hasNext：true表示要发起微信支付，false表示已支付成功
				if (!paymentdata.hasNext) {
					// 0元支付成功（表示写支付记录成功，并未真的进行支付）
					console.log("0元支付成功");
					/**
					 * 延时查询业务是否处理成功；
					 * 1.处理成功，则跳转到订单详情
					 * 2.处理未成功，则提交流程(再次进行业务处理)
					 */
					setTimeout(() => {
						// 根据订单id判断后端是否已经处理好业务
						this.getJoinRecordDetails(this.form.orderId);
					}, 1500);
					return;
				}
				
				// 开始发起支付动作，进入到这里表示 hasNext = true，需要调用发起微信支付*/
				let that = this;
				let payTag = '';// 记录是否支付成功。0:未支付成功；1:支付成功
				wx.requestPayment({
					...paymentdata,
					success(res) {
						// 此处只能返回通信成功，返回的并不是支付成功，只能在complete中进行业务处理
						console.log("支付成功", res);
						payTag = '1';// 支付成功
					},
					fail(err) {
						console.log("支付失败", err);
						// that.showMSG('error', '支付失败！');
						that.payType_show = false; // 关闭 选择支付的方式
						that.isClick = false; // 设置按钮为可点击
						payTag = '0';// 支付失败
					},
					complete(res) {
						/**
						 * 延时查询业务是否处理成功
						 * 1.业务处理成功，则弹出分享海报
						 * 2.业务处理未成功，则再执行一次业务处理
						 */
						if(payTag == '1'){// 支付成功才会执行
							setTimeout(() => {
								// 根据订单id判断后端是否已经处理好业务
								that.getJoinRecordDetails(that.form.orderId);
							}, 1500);
						}
					}
				});
			},
			
			/**
			 * 根据订单id判断后端是否已经处理好业务
			 */
			async getJoinRecordDetails(orderId){
				let result = await this.$u.api.unifyMiniRestGet({
					systemid: "meily",
					url: "/provide/samples/sub/info/byOrderId/" + orderId,
					loading: true // 默认发起请求会有一个全局的Loading，设置false可去掉
				});
				if (result.code == 200) {
					if(result.data){
						// 1.处理成功，则弹出公众号弹窗
						this.orderDetail = result.data;
						this.payType_show = false;
						this.official_account_show = true;
					} else {
						// 2.处理未成功，则提交流程(再次进行业务处理)，不在小程序处理业务了
						// this.receive();
						this.payType_show = false; // 关闭 选择支付的方式
						this.isClick = false; // 设置按钮为可点击
						this.showMSG('error', '出错啦！');
					}
				} else {
					this.$u.toast(result.msg)
				}
			},
			
			/**
			 * 确定领取(保存参与记录)
			 */
			async receive() {
				let result = await this.$u.api.unifyMiniRest({
					systemid: "meily",
					url: "/provide/samples/sub/receive",
					id: this.orderDetail.id,// 领取记录唯一id
					partnerId: uni.getStorageSync('userInfo').userId,// 参与者id
					partnerName: uni.getStorageSync('userInfo').nickName,// 参与者昵称
					partnerAvatarUrl: uni.getStorageSync('userInfo').avatarUrl,// 参与者头像
					initiatorId: this.form.initiatorId,
					initiatorName: this.form.initiatorName,
					subject: this.form.subject,
					joinEndTime: this.form.joinEndTime,
					endTime: this.form.joinEndTime,
					mainId: this.form.id,
					mainTaskNumber: this.form.taskNumber,
					sceneAssetsId: this.form.sceneAssetsId,
					sceneId: this.form.sceneId,
					consigneeName: this.addressObj.Name,// 收货人姓名
					consigneePhoneNum: this.addressObj.PhoneNum,// 手机号码
					consigneeAddress: this.addressObj.Region + "-" + this.addressObj.StreetVillage + " " + this.addressObj.Address,// 收货地址
					orderRemarks: this.orderRemarks,// 订单备注
					/* supplierId: this.selectedSupplier.userId,
					supplierName: this.selectedSupplier.nickName,
					supplier: JSON.stringify(this.selectedSupplier), */
					samplePrice: this.form.samplePrice,
					goodsId: this.form.goodsId,
					goodsNo: this.form.goodsNo,
					goodsName: this.form.goodsName,
					goodsImages: this.form.goodsImages,
					specification: this.form.specification,
					orderStatus: '待发货',
					orderId: this.form.orderId,
					quantity: "1",
					payAmount: this.form.samplePrice,
					useDeduction: this.useDeduction,// 是否使用抵扣
					deductionAmount: this.deductionAmount,// 抵扣金额
					loading: true // 默认发起请求会有一个全局的Loading，设置false可去掉
				});
				if (result.code == '200') {
					this.orderDetail = result.data;
					this.payType_show = false;
					this.official_account_show = true;
				} else {
					// 设置按钮为可点击
					this.isClick = false;
					this.$u.toast(result.msg);
				}
			},
			
			/**
			 * 选择收货地址
			 */
			toSelectAddress() {
				this.$u.route('/pages_tabbar_contact/personal_contact/AddressList?type=select');
			},
			
			/**
			 * 关注公众号
			 */
			// followOfficialAccount() {
			// 	this.official_account_show = true
			// },
			
			/** 
			 * 关闭公众号弹窗，跳转到订单详情
			 */
			closeOfficialAccount() {
				uni.reLaunch({url: '/pages_private_scene2/provide_samples/order_details?recordId=' + this.orderDetail.id + '&comeback=1'});
			},
			
			/**
			 * 格式化订单名字（名字超长处理）
			 * name：需要处理的字段
			 * MaxLength：要保留的最大长度，包含...
			 */
			formatSubject(name, MaxLength) {
				let cutName = "";
				if (name.length > MaxLength) {
					// 超出的长度，需要截取
					let cutLength = name.length - (name.length - MaxLength) - 3; // 3表示三个省略号的长度
					cutName = name.substring(0, cutLength) + "...";
				} else {
					cutName = name;
				}
				return cutName;
			},
			
			/**
			 * 【重要！样品领取前请仔细阅读】 
			 */
			showRules(){
				if(this.show_rule){
					this.iconName = 'arrow-right'
					this.show_rule = false
				} else {
					this.iconName = 'arrow-down'
					this.show_rule = true
				}
			},
			
			/**
			 * 跳转到销售机会页面
			 */
			async toGoodsDetails(){
				this.$u.route('/pages_private_scene2/GroupPurchase/DistributionGoods?goodsNo=' + this.form.goodsNo + '&goodsId=' + this.form.goodsId);
			},
			
			/**
			 * 关注公众号
			 */
			followOfficialAccount() {
				this.routeAD(this.officialAccountUrl,'outside')
			},
		}
	}
</script>


<style scoped>
	aui-flexView {
		width: 100%;
		height: 100%;
		margin: 0 auto;
		display: -webkit-box;
		display: -webkit-flex;
		display: -ms-flexbox;
		display: flex;
		-webkit-box-orient: vertical;
		-webkit-box-direction: normal;
		-webkit-flex-direction: column;
		-ms-flex-direction: column;
		flex-direction: column;
	}

	.aui-scrollView {
		width: 100%;
		height: 100%;
		-webkit-box-flex: 1;
		-webkit-flex: 1;
		-ms-flex: 1;
		flex: 1;
		overflow-y: auto;
		overflow-x: hidden;
		-webkit-overflow-scrolling: touch;
		position: relative;
		margin-top: 0;
	}

	.aui-navBar {
		height: 44px;
		position: relative;
		display: -webkit-box;
		display: -webkit-flex;
		display: -ms-flexbox;
		display: flex;
		z-index: 1002;
		background: #f7f7f7;
	}

	.b-line {
		position: relative;
	}

	.b-line:after {
		content: '';
		position: absolute;
		z-index: 2;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 1px;
		border-bottom: 1px solid #e2e2e2;
		-webkit-transform: scaleY(0.5);
		transform: scaleY(0.5);
		-webkit-transform-origin: 0 100%;
		transform-origin: 0 100%;
	}

	.aui-navBar-item {
		height: 44px;
		min-width: 25%;
		-webkit-box-flex: 0;
		-webkit-flex: 0 0 25%;
		-ms-flex: 0 0 25%;
		flex: 0 0 25%;
		padding: 0 0.9rem;
		display: -webkit-box;
		display: -webkit-flex;
		display: -ms-flexbox;
		display: flex;
		-webkit-box-align: center;
		-webkit-align-items: center;
		-ms-flex-align: center;
		align-items: center;
		font-size: 0.7rem;
		white-space: nowrap;
		overflow: hidden;
		color: #353535;
		position: relative;
	}

	.aui-navBar-item:first-child {
		-webkit-box-ordinal-group: 2;
		-webkit-order: 1;
		-ms-flex-order: 1;
		order: 1;
		margin-right: -25%;
		font-size: 0.9rem;
		font-weight: bold;
	}

	.aui-navBar-item:last-child {
		-webkit-box-ordinal-group: 4;
		-webkit-order: 3;
		-ms-flex-order: 3;
		order: 3;
		-webkit-box-pack: end;
		-webkit-justify-content: flex-end;
		-ms-flex-pack: end;
		justify-content: flex-end;
	}

	.aui-center {
		-webkit-box-ordinal-group: 3;
		-webkit-order: 2;
		-ms-flex-order: 2;
		order: 2;
		display: -webkit-box;
		display: -webkit-flex;
		display: -ms-flexbox;
		display: flex;
		-webkit-box-pack: center;
		-webkit-justify-content: center;
		-ms-flex-pack: center;
		justify-content: center;
		-webkit-box-align: center;
		-webkit-align-items: center;
		-ms-flex-align: center;
		align-items: center;
		height: 44px;
		width: 50%;
		margin-left: 25%;
	}

	.aui-center-title {
		text-align: center;
		width: 100%;
		white-space: nowrap;
		overflow: hidden;
		display: block;
		text-overflow: ellipsis;
		font-size: 0.95rem;
		color: #333;
	}

	.icon {
		width: 20px;
		height: 20px;
		display: block;
		border: none;
		float: left;
		background-size: 20px;
		background-repeat: no-repeat;
	}

	.aui-flex {
		display: -webkit-box;
		display: -webkit-flex;
		display: flex;
		-webkit-box-align: center;
		-webkit-align-items: center;
		align-items: center;
		padding: 30rpx;
		position: relative;
	}

	.aui-flex-box {
		-webkit-box-flex: 1;
		-webkit-flex: 1;
		flex: 1;
		min-width: 0;
		font-size: 14px;
		color: #333;
	}

	.aui-flex-triangle {
		position: relative;
		font-size: 14px;
		padding-right: 15px;
	}

	.aui-flex-triangle:before {
		content: '';
		width: 0;
		height: 0;
		border-width: 5px 0px 5px 8px;
		border-style: solid;
		border-color: transparent transparent transparent #7b7b7b;
		position: absolute;
		top: 6px;
		right: 0;
		border-radius: 1;
	}

	.aui-choice-white {
		background: #fff;
	}

	.aui-order-box {
		padding: 10px 20px;
	}

	.aui-flex-goods {
		margin-right: .8em;
		width: 80px;
		height: 80px;
		line-height: 80px;
		text-align: center;
	}

	.aui-flex-goods img {
		width: 100%;
		max-height: 100%;
		vertical-align: top;
	}

	.aui-flex-default {
		/* background: #f3f1f1; */
	}

	.aui-flex-default h2 {
		font-size: 14px;
		width: auto;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		word-wrap: normal;
		word-wrap: break-word;
		word-break: break-all;
		padding-bottom: 5px;
	}

	.aui-flex-default p {
		color: #999999;
		font-size: 12px;
	}

	.aui-flex-clear {
		padding: 0;
		/* margin-top: 20px; */
	}

	.aui-flex-clear .aui-flex-box {
		color: #f21956;
		font-weight: bold;
	}

	.aui-mar15 {
		margin-bottom: 15px;
	}

	.aui-flex-triangle-clear:before {
		border-color: #fff;
	}

	.aui-flex-box h2 {
		font-size: 16px;
		padding-bottom: 5px;
	}

	.aui-flex-box h3 {
		font-size: 14px;
		padding-bottom: 5px;
	}

	.aui-flex-box p {
		font-size: 12px;
		color: #999;
		line-height: 1.2;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 1;
	}

	.aui-bar-footer {
		/* line-height: 52px; */
		height: 190rpx;
		background: #fff;
		box-shadow: 0 -2px 10px #ddd;
		position: fixed;
		z-index: 999;
		bottom: 0;
		left: 0;
		width: 100%;
	}

	.aui-btn-button {
		background: #f21956;
		padding: 0 25px;
		color: #fff;
		font-size: 14px;
	}

	.aui-bar-footer .aui-flex {
		padding: 0;
	}

	.aui-bar-footer .aui-flex-box {
		padding-left: 15px;
	}

	.aui-bar-footer .aui-flex-box span {
		font-style: normal;
		color: #f21956;
	}

	.cnt {
		padding-top: 1px;
		color: #e61111;
		position: relative;
		line-height: 22px;
		font-size: 14px;
		font-weight: 500;
	}

	.popup-box {
		padding-bottom: 50rpx;
		padding-top: 50rpx;
	}

	.popup-item {
		height: 100rpx;
		line-height: 100rpx;
		text-align: center;
		font-size: 33rpx;
	}

	.aui-tag {
		display: inline
	}

	.cont-right {
		display: flex;
		flex-direction: column;
	}

	.cont-right p {
		width: 100%;
	}

	.xmname {
		opacity: 0.7;
		font-family: PingFangSC-Regular;
		font-size: 14px;
		color: #3B353C;
		line-height: 22px;
	}

	.name {
		font-family: PingFangSC-Regular;
		font-size: 14px;
		color: #3B353C;
		letter-spacing: 0;
		line-height: 22px;
	}

	.solitaire-title {
		display: -webkit-box;
		/*必须结合的属性,将对象作为弹性伸缩盒子模型显示*/
		-webkit-line-clamp: 1;
		/*设置多少行*/
		-webkit-box-orient: vertical;
		/*必须结合的属性,设置或检索伸缩盒对象的子元素的排列方式*/
		overflow: hidden;
		/*文本会被修剪，并且剩余的部分不可见*/
		text-overflow: ellipsis;
		/*显示省略号来代表被修剪的文本*/
		font-size: 14px;
	}
	
	.color-red {
		color: #f95c0f;
	}
	
	.font-weight-550 {
		font-weight: 550;
	}
	
	.success-modal-bottom {
		background: url(https://www-1308272144.cos.ap-guangzhou.myqcloud.com/Meily/icon/Share/ShareTips.png) no-repeat;
		background-size: 100%;
		height: 60rpx;
	}
	
	.success-modal-share {
		display: flex;
		justify-content: center;
		padding-top: 280rpx;
	}
	
	.success-modal-content {
		background: url(https://www-1308272144.cos.ap-guangzhou.myqcloud.com/Meily/icon/Share/ShareBG.png) no-repeat;
		background-size: 100% 100%;
		height: 630rpx;
		width: 500rpx;
	}
	
	.buy-goods-share {
		font-size: 30rpx;
		width: 250rpx;
		height: 70rpx;
		padding: 0;
		background: url(https://www-1308272144.cos.ap-guangzhou.myqcloud.com/Meily/icon/Share/ShareBtn.png) repeat;
		background-size: cover;
		border: none !important;
		padding-left: 0rpx !important;
		padding-right: 0rpx !important;
		padding-top: 6rpx !important;
	}
	
	.mask-solt {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100%;
	}
	
	.mask-close {
		display: flex;
		justify-content: center;
	}
	
	.official-account-bg {
		background: url(https://www-1308272144.cos.ap-guangzhou.myqcloud.com/Meily/icon/Share/ShareofficialAccount.png) no-repeat;background-size: 100% 100%;
		width: 540rpx;
		height: 780rpx;
	}
	
	.default-tag {
		padding: 0rpx 5rpx;
		background-color: #e5392b;
		color: #ffffff;
		border-radius: 5rpx;
		font-size: 20rpx;
		margin-right: 10rpx;
	}
	
	.aui-flex2 {
		display: -webkit-box;
		display: -webkit-flex;
		display: flex;
		-webkit-box-align: center;
		-webkit-align-items: center;
		align-items: center;
		padding: 20rpx 30rpx;
		position: relative;
	}
	
	.border-radius-30 {
		border-radius: 30rpx;
	}
	
	.address1 {
		width: 560rpx;
		overflow:hidden;
		text-overflow:ellipsis;
		display:-webkit-box;
		-webkit-box-orient:vertical;
		-webkit-line-clamp:1;
	}
	
	.v-sperate {
		height: 10rpx;
		background: #f7f1f7;
	}
	
	.width93 {
		width: 93%;
		margin: 0 auto;
	}
	
	.modal-item {
		/* margin: 40rpx 0rpx; */
		height: 100rpx;
		line-height: 40rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		/* color: #9f9d9e; */
		/* border-top: 1rpx solid #eeeded; */
	}
	
	.rule-title {
		height: 100rpx;
		line-height: 100rpx;
		width: 90%;
		margin: 0 auto;
		font-weight: bold;
	}
	
	.rule-content {
		width: 90%;
		margin: 0 auto;
		padding-bottom: 20rpx;
		border-bottom: 2rpx solid #f4f4f4;
	}
	.notice-bar {
		background-color: #f7591f;
		color: #ffffff;
		text-align: center;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 24rpx;
		width: 100%;
	}
</style>
